<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <div class="daohang">
      <a @click="navigateTo('/repair-list-user')">报修列表</a>
      <span>&nbsp; >&nbsp;</span>我要报修
    </div>
    <hr>

    <!-- 表单 -->
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <!-- 左侧表单项 -->
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="报修人" prop="repairUserName">
            <el-input
                v-model="form.repairUserName"
                placeholder="姓名最长10位"
                class="input-style"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="repairUserPhone">
            <el-input
                v-model="form.repairUserPhone"
                placeholder="联系方式为11位电话号码"
                class="input-style"
            ></el-input>
          </el-form-item>
          <el-form-item label="维修区域" prop="repairArea">
            <el-select v-model="form.repairArea" placeholder="请选择">
              <el-option
                  v-for="item in regionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="维修项目" prop="repairCategoryId">
            <el-select v-model="form.repairCategoryId" placeholder="请选择">
              <el-option
                  v-for="item in projectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预约维修时间" prop="appointmentTime">
            <el-date-picker
                v-model="form.appointmentTime"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                :disabled-time="disabledTime"
            />
          </el-form-item>
        </el-col>

        <!-- 右侧表单项 -->
        <el-col :span="12">
          <el-form-item label="图片上传" prop="field131">
            <el-upload
                action="http://192.168.50.8:10005/repaircenter/repairFileUpload/upload"
                list-type="picture-card"
                :headers="headers"
                :auto-upload="true"
                :on-change="handleFileChange"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :file-list="uploadedImages"
            >
              <el-icon v-if="isUploadVisible">
                <Plus/>
              </el-icon>
              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                  <span class="el-upload-list__item-actions">
                    <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><ZoomIn/></el-icon>
                    </span>
                    <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                    >
                      <el-icon><Delete/></el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image"/>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 维修内容 -->
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="维修内容" prop="repairContent">
            <el-input
                type="textarea"
                v-model="form.repairContent"
                placeholder="维修内容不超过50个字"
                class="input-style"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 详细地点 -->
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="详细地点" prop="detailedAddress">
            <el-input
                v-model="form.detailedAddress"
                placeholder="详细地点不超过30个字"
                class="input-style"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 提交按钮 -->
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="submitForm">确认提交</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElRow,
  ElCol,
  ElButton,
  ElDatePicker,
  ElUpload,
  ElDialog,
  ElIcon,
  ElMessageBox,
  ElMessage
} from 'element-plus';
import {ref, onMounted} from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

import {Delete, Download, Plus, ZoomIn} from '@element-plus/icons-vue';

const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const disabled = ref(false);

const form = ref({
  repairContent: "",
  repairCategoryId: "",
  repairType: "",
  repairArea: "",
  detailedAddress: "",
  repairPhotoIds: [],
  repairUser: "",
  repairUserName: "",
  repairUserPhone: "",
  appointmentTime: "",
});

const regionOptions = ref([]);
const projectOptions = ref([]);
const field131fileList = ref([]);
const isUploadVisible = ref(true);
const listLengthTag = ref(0);
const uploadedImages = ref([]);
const router = useRouter();
// 定义 formRef 引用
const formRef = ref(null);
const headers = ref({
  token: localStorage.getItem("token")
});
const navigateTo=(route)=>{
  router.push(route)
};
const disabledDate = (time) => {
  const now = new Date(); // 当前时间
  // 禁用今天之前的日期，但保留今天
  return time.getTime() < new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
};
const disabledTime = (time) => {
  const now = new Date(); // 当前时间
  const selectedDate = new Date(time); // 用户选择的日期
  return selectedDate.getTime() < now.getTime();
};
// 定义 rules
const rules = ref({
  repairUserName: [
    { required: true, message: '请输入报修人姓名', trigger: 'blur' },
    { max: 10, message: '姓名不能超过10个字符', trigger: 'blur'}
  ],
  repairUserPhone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ],
  repairArea: [
    { required: true, message: '请选择维修区域', trigger: 'change' }
  ],
  repairCategoryId: [
    { required: true, message: '请选择维修项目', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约维修时间', trigger: 'change' }
  ],
  repairPhotoIds: [
    {
      validator: (rule, value) => {
        if (value.length <= 2) return true;
        return new Error('最多上传两张图片');
      },
      trigger: 'change'
    }
  ],
  repairContent: [
    { required: true, message: '请输入维修内容', trigger: 'blur' },
    { max: 50, message: '维修内容不能超过50个字', trigger: 'blur' }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 30, message: '详细地址不能超过30个字', trigger: 'blur' }
  ]
});
const handleFileChange = (file, fileList) => {
  if (fileList.length > 2) {
    ElMessage.warning("最多只能上传 2 张图片");
    fileList.pop(); // 移除最后一个文件
    return;
  }

  // 清空旧的图片 ID 数组
  form.value.repairPhotoIds = [];

  // 更新 uploadedImages 和 field131fileList
  uploadedImages.value = fileList.map(f => ({
    url: f.url || URL.createObjectURL(f.raw), // 确保有 url 字段
    id: f.id || null, // 确保有 id 字段
    name: f.name,
    ...f
  }));
  field131fileList.value = [...fileList]; // 使用扩展运算符确保深拷贝
  listLengthTag.value = fileList.length;

  // 控制上传按钮的显示状态
  if (fileList.length >= 2) {
    isUploadVisible.value = false; // 隐藏上传按钮
  } else {
    isUploadVisible.value = true; // 显示上传按钮
  }

  // 处理上传成功的文件
  fileList.forEach(f => {
    if (f.status === 'success' && f.response) {
      const repairUploadId = f.response.data[0].repairUploadId;
      const filePath = f.response.data[0].filePath;
      const index = uploadedImages.value.findIndex(item => item.uid === f.uid);
      if (index !== -1) {
        uploadedImages.value[index] = {
          ...uploadedImages.value[index],
          id: repairUploadId,
          url: filePath
        };
        form.value.repairPhotoIds.push(repairUploadId);
      }
    }
  });
};

const handleRemove = (file) => {
  console.log('handleRemove called with file:', file);
  const index = uploadedImages.value.findIndex(item => item.uid === file.uid); // 使用 uid 进行查找
  if (index !== -1) {
    removeImage(index);
  }
};

const beforeRemove = (file) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`).then(() => true).catch(() => false);
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const fetchRegionOptions = async () => {
  try {
    const response = await axios.get("/user/areaCode/listAreaCode"); // 修改接口路径
    if (response.data.code === 200) {
      regionOptions.value = response.data.data.map((area) => ({
        value: area.areaCodeId, // 使用正确的字段名
        label: area.areaCodeName, // 根据实际情况调整字段名
      }));
    } else {
      ElMessage.error("获取区域列表失败");
    }
  } catch (error) {
    ElMessage.error("获取区域列表失败");
    console.error(error);
  }
};

const fetchRepairCategories = async () => {
  try {
    const response = await axios.get(
        "/repaircenter/repairCategory/listAll"
    );

    if (response.data.code === 200) {
      projectOptions.value = response.data.data.map((category) => ({
        value: category.repairCategoryId, // 假设返回的数据中有一个 repairCategoryId 字段作为 value
        label: category.categoryName, // 假设返回的数据中有一个 categoryName 字段作为 label
      }));
    } else {
      ElMessage.error("获取维修类型列表失败");
    }
  } catch (error) {
    ElMessage.error("获取维修类型列表失败");
    console.error(error);
  }
};

const removeImage = (index) => {
  console.log('removeImage called with index:', index);
  const imageId = uploadedImages.value[index]?.id; // 确保有 id 字段
  if (!imageId) return;

  // 移除图片 ID
  form.value.repairPhotoIds = form.value.repairPhotoIds.filter(id => id !== imageId);

  // 更新 uploadedImages 数组
  uploadedImages.value.splice(index, 1);

  // 如果图片数量小于2，重新显示上传框
  if (uploadedImages.value.length < 2) {
    isUploadVisible.value = true;
  }

  // 调用后端删除接口
  deleteImage(imageId);
};

const deleteImage = (imageId) => {
  axios.delete(`http://localhost:10005/repaircenter/repairFileUpload/deleteById?id=${imageId}`)
      .then(response => {
        if (response.data.code === 200) {
          ElMessage.success("图片删除成功");
        } else {
          ElMessage.error("图片删除失败，请重试");
        }
      })
      .catch(error => {
        console.error('Error:', error);
        ElMessage.error("图片删除失败，请重试");
      });
};

const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 查找 repairCategoryId 对应的名称
      const repairCategory = projectOptions.value.find(category => category.value === form.value.repairCategoryId);
      const repairTypeName = repairCategory ? repairCategory.label : "";

      // 查找 repairArea 对应的名称
      const region = regionOptions.value.find(region => region.value === form.value.repairArea);
      const repairAreaName = region ? region.value : "";

      // 获取当前用户的 ID
      const getCurrentUserId = () => {
        // 这里可以是获取当前用户 ID 的逻辑，例如从 Vuex store 或 localStorage 中获取
        return localStorage.getItem('userId'); // 示例：从 localStorage 获取用户 ID
      };

      const formData = {
        repairContent: form.value.repairContent,
        repairCategoryId: form.value.repairCategoryId,
        repairType: repairTypeName, // 使用对应的名称
        repairArea: repairAreaName, // 使用对应的名称
        detailedAddress: form.value.detailedAddress,
        repairPhotoIds: form.value.repairPhotoIds.map((id) => parseInt(id)), // 将字符串 ID 转换为整数
        repairUser: getCurrentUserId(), // 使用当前用户的 ID
        repairUserName: form.value.repairUserName,
        repairUserPhone: form.value.repairUserPhone,
        appointmentTime: form.value.appointmentTime,
      };

      try {
        const response = await axios.post(
            "/repaircenter/repair/addRepair",
            formData
        );

        if (response.data.code === 200) {
          ElMessage.success("提交成功");
          router.push('/repair-list-user');
        } else {
          ElMessage.error("提交失败，请重试");
        }
      } catch (error) {
        ElMessage.error("提交失败，请重试");
        console.error(error);
      }
      console.log(formData);
    } else {
      ElMessage.error("请填写完整信息");
    }
  });
};

onMounted(() => {
  fetchRepairCategories();
  fetchRegionOptions();
});
</script>

<style scoped>
.el-upload__tip {
  line-height: 1.2;
}

.article-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  margin-top: 110px;
}

.daohang {
  width: 83%;
  text-align: left;
  border-bottom: 1px solid #00000017;
  background: url(../assets/img/icon-location-blue.png) no-repeat -8px 8px;
  background-position: 12px 0px;
  padding-left: 30px;
}

.daohang > a,
.daohang > span {
  color: #0000004d;
}

button {
  margin-left: 73%;
  margin-bottom: 15px;
}

.article-card:hover {
  background-color: rgba(0, 0, 0, 0);
}

/* 如果需要根据父类 .hide_box 控制显示 */
.hide_box .el-upload--picture-card {
  display: none;
}
</style>
